/*******************************************************************
 *
 * Copyright (C), 2021-2022, Letstrong, All rights reserved.
 *
 * Author      : 
 * Create Time : 2020-11-05
 * Version     : v0.1
 * Description : 
 *******************************************************************/
 
/*----------------------------Head file----------------------------*/
#include "hal_utc.h"
#include "hal_flash.h"
#include "app_reset.h"
#include "app_global_data.h"
#include "user_config.h"

#define APP_RESET_LOG_EN	0

#if APP_RESET_LOG_EN
#include "log.h"
#define APP_RST_LOG			LOG_DEBUG
#else
#define APP_RST_LOG(...)
#endif

/*----------------------------macro file---------------------------*/

/*----------------------------type define--------------------------*/
typedef struct{
	uint16_t id;
	uint32_t time_base;
} timebase_t;

/*----------------------------var define---------------------------*/

/*-------------------------func declaration------------------------*/

/*-----------------------------------------------------------------*/

void app_system_reset(void)
{
	timebase_t info;
	
	info.time_base = hal_utc_seconds_get();
	if(info.time_base <= 0) {
		app_platform_reset();
		return;
	}
	
	info.id = SOFT_RESET_VALID_ID;
	hal_flash_erase_sector(TEMP_DATA_RST_ADDR);
	hal_flash_write(TEMP_DATA_RST_ADDR, (uint8_t*)&info, sizeof(info));
	app_platform_reset();
}


void app_ship_mode_reset(void)
{
	uint16_t reset_reason = SHIP_MODE_VALID_ID;
	
	hal_flash_erase_sector(TEMP_DATA_RST_ADDR);
	hal_flash_write(TEMP_DATA_RST_ADDR, (uint8_t*)&reset_reason, sizeof(reset_reason));
	app_platform_reset();
}


uint8_t app_system_reset_reason_get(void)
{
	uint16_t reset_reason = RST_REASON_NULL;
	hal_flash_read(TEMP_DATA_RST_ADDR, (uint8_t*)&reset_reason, sizeof(reset_reason));
	if(SOFT_RESET_VALID_ID == reset_reason) {
		//Do not erase here, we need read base time later.
		return RST_REASON_SOFT_RST;
	}
	if(SHIP_MODE_VALID_ID == reset_reason) {
		hal_flash_erase_sector(TEMP_DATA_RST_ADDR);
		return RST_REASON_SHIP_MODE_ENTER;
	}
	else if(SHIP_MODE_WAKE_ID == reset_reason) {
		hal_flash_erase_sector(TEMP_DATA_RST_ADDR);
		return RST_REASON_SHIP_MODE_WAKE;
	}
	else {
		return RST_REASON_NULL;
	}
}


void app_system_reset_data_init(void)
{
	timebase_t info;
	
	g_app_data.sys.rst_reason = app_system_reset_reason_get();
	if(RST_REASON_SOFT_RST == g_app_data.sys.rst_reason) {
		hal_flash_read(TEMP_DATA_RST_ADDR, (uint8_t*)&info, sizeof(info));
		hal_utc_seconds_set(info.time_base);
		hal_flash_erase_sector(TEMP_DATA_RST_ADDR);
	}
}

